package com.chenliwu.demo.java8.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * CompletableFuture Demo
 *
 * @author chenliwu
 * @since 2023-02-11
 */
public class CompletableFutureDemo {

    public static void main(String[] args) {
        test_runAsync();
        test_supplyAsync();
    }

    /**
     * CompletableFuture runAsync异步操作
     */
    static void test_runAsync() {
        // runAsync() 以Runnable函数式接口类型为参数，没有返回结果
        CompletableFuture.runAsync(() -> {
            System.out.println("CompletableFuture异步操作");
        });
        System.out.println("test_completeablefuture_async");
    }

    /**
     * CompletableFuture supplyAsync异步操作
     */
    static void test_supplyAsync() {
        // supplyAsync() 以Supplier函数式接口类型为参数，返回结果类型为U；Supplier接口的 get()是有返回值的(会阻塞)
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("有返回值的异步任务");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "supplyAsync result";
        });
        try {
            String result = future.get();
            System.out.println("test_supplyAsync:" + result);
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
